package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.exception.BizIllegalException;
import com.hmall.common.utils.BeanUtils;

import com.hmall.item.domain.dto.ItemDTO;
import com.hmall.item.domain.dto.OrderDetailDTO;
import com.hmall.item.domain.po.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 虎哥
 */
@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Override
    @Transactional
    public void deductStock(List<OrderDetailDTO> items) {
//        String sqlStatement = "com.hmall.mapper.ItemMapper.updateStock";
        String sqlStatement = "com.hmall.item.mapper.ItemMapper.updateStock";
        boolean r = false;
        try {
            r = executeBatch(items, (sqlSession, entity) -> sqlSession.update(sqlStatement, entity));
        } catch (Exception e) {
            throw new BizIllegalException("更新库存异常，可能是库存不足!", e);
        }
        if (!r) {
            throw new BizIllegalException("库存不足！");
        }

    }

    @Override
    public List<ItemDTO> queryItemByIds(Collection<Long> ids) {
        return BeanUtils.copyList(listByIds(ids), ItemDTO.class);
    }

    @Override
    public void restoreStock(Map<Long, List<OrderDetailDTO>> map) {
        //  1.根据id查询商品信息
        Set<Long> itemIds = map.keySet();
        for (Long itemId : itemIds) {
            //  2.将商品的数量查出来
            Item item = getById(itemId);
            Integer num = map.get(itemId).get(0).getNum();
            Item updateItem = new Item();
            updateItem.setStock(item.getStock() + num);
            updateItem.setId(itemId);
            // 3.将商品的数量加上订单中的数量更新回去
            LambdaUpdateWrapper<Item> itemLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            update(updateItem, itemLambdaUpdateWrapper.eq(Item::getStock, item.getStock()));
        }
    }
}
